<?php

namespace app\model\user;

use app\base\BaseModel;
use app\libs\Util;
use app\model\game\GameProcessModel;
use app\model\order\OrderModel;
use think\facade\Db;

/**
 * 模型-UserParentModel
 * Class UserParent
 * @package app\model
 */
class UserParentModel extends BaseModel
{
    protected $name = 'user_parent';

    public static $CONDITION = [
        'C' => [
            'level' => 1, //用户等级对应数字
            'num' => 100000,     //升级瞒住条件
            'num_line' => 1000000,//直推用户数
            'unit' => "V"   //升级单位
        ],
        'V' => [
            'level' => 2, //用户等级对应数字
            'num' => 100000,     //升级瞒住条件
            'num_line' => 1000000,//直推用户数
            'unit' => "V1"   //升级单位
        ],
        'V1' => [
            'level' => 3, //用户等级对应数字
            'num' => 1,     //升级瞒住条件
            'num_line' => 1,//直推用户数
            'unit' => "V"   //升级单位
        ],
        'V2' => [
            'level' => 4, //用户等级对应数字
            'num' => 9,
            'num_line' => 9,
            'unit' => "V"
        ], 'X1' => [
            'level' => 5, //用户等级对应数字
            'num' => 3,
            'num_line' => 3,
            'unit' => "V2"
        ], 'X2' => [
            'level' => 6, //用户等级对应数字
            'num' => 3,
            'num_line' => 3,
            'unit' => "X1"
        ], 'X3' => [
            'level' => 7, //用户等级对应数字
            'num' => 5,
            'num_line' => 4,
            'unit' => "X2"
        ], 'X4' => [
            'level' => 8, //用户等级对应数字
            'num' => 5,
            'num_line' => 5,
            'unit' => "X3"
        ]
    ];

    /**
     * 获取分页列表
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @return array
     */
    public function getPageData($current_page, $list_rows, $field = '*')
    {
        $dataList = $this
            ->field($field)
            ->order('create_time', 'desc')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 用户等级变化  刷新全部父级关系
     * @param string $user_id
     * @param string $level
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function upVipParent($user_id = '', $level = 'V')
    {
        // V2 0
        //可能需要枷锁处理 防止高并发数据重复更新
        $data = $this->where('user_id', $user_id)->find();
        if ($data['level'] == $level) {
            return true;
        }
        $up_date = [
            'level' => $level
        ];
        UserModel::setPopLevel([$user_id], $level);
        $this->where('user_id', $user_id)->update($up_date);
//        return;
        $parent = json_decode($data['parent'], true);
        if (empty($parent)) {
            return true;
        }
        foreach ($parent as $value) {
            self::upChildrenSubset($value);
        }
        return true;
    }

    /**
     * 强行设置用户等级变化
     * @param string $user_id
     * @param string $level
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setLevelParent($user_id = '', $level = 'V2')
    {
        // V2 0
        //可能需要枷锁处理 防止高并发数据重复更新
        $data = $this->where('user_id', $user_id)->find();
        if ($data['level'] == $level) {
            return true;
        }
        $up_date = [
            'level' => $level,
            'status' => 2
        ];
        UserModel::setPopLevel([$user_id], $level);
        $this->where('user_id', $user_id)->update($up_date);
        $parent = json_decode($data['parent'], true);
        if (empty($parent)) {
            return true;
        }
        foreach ($parent as $value) {
            self::upChildrenSubset($value);
        }
        return true;
    }

    /**
     * 刷新父级变动级别
     * @param string $user_id
     */
    public static function upChildrenSubset($user_id = "")
    {
        if (empty($user_id)) {
            return true;
        }
        $temp_data = self::where('user_id', $user_id)->find();
        $sql = "SELECT `user_id`,`level`,`parent` FROM `t_user_parent` WHERE JSON_CONTAINS(`parent`, '" . $user_id . "', '$')";
        $list = Db::query($sql);
        $v = 0;
        $v_1 = 0;
        $v2 = 0;
        $v2_1 = 0;
        $x1 = 0;
        $x1_1 = 0;
        $x2 = 0;
        $x2_1 = 0;
        $x3 = 0;
        $x3_1 = 0;
        $x4 = 0;
        $x4_1 = 0;
        $branch_arr = [];
        $branch_arr1 = [];
        $branch_arr2 = [];
        $branch_arr3 = [];
        $branch_arr4 = [];
        foreach ($list as $value) {
            $parent = json_decode($value['parent'], true);
            switch ($value['level']) {
                case 'V':
                case 'V1':
                    if ($user_id == $parent[0]) {
                        //如果是直推关系 直推关系加一
                        $v_1 += 1;
                    }
                    $v += 1;
                    break;
                case 'V2':
                    if ($user_id == $parent[0]) {
                        //如果是直推关系 直推关系加一
                        $v2_1 += 1;
                    }
                    $index = array_search($user_id, $parent);
                    if ($index == 0) {
                        $branch_arr[] = $value['user_id'];
                    }
                    if (intval($index) - 1 >= 0) {
                        $branch_arr[] = $parent[intval($index) - 1];
                    }
                    $v2 += 1;
                    break;
                case 'X1':
                    if ($user_id == $parent[0]) {
                        //如果是直推关系 直推关系加一
                        $x1_1 += 1;
                    }
                    $index = array_search($user_id, $parent);
                    if ($index == 0) {
                        $branch_arr[] = $value['user_id'];
                        $branch_arr1[] = $value['user_id'];
                    }
                    if (intval($index) - 1 >= 0) {
                        $branch_arr[] = $parent[intval($index) - 1];
                        $branch_arr1[] = $parent[intval($index) - 1];
                    }
                    $x1 += 1;
                    break;
                case 'X2':
                    if ($user_id == $parent[0]) {
                        //如果是直推关系 直推关系加一
                        $x2_1 += 1;
                    }
                    $index = array_search($user_id, $parent);
                    if ($index == 0) {
                        $branch_arr[] = $value['user_id'];
                        $branch_arr1[] = $value['user_id'];
                        $branch_arr2[] = $value['user_id'];
                    }
                    if (intval($index) - 1 >= 0) {
                        $branch_arr[] = $parent[intval($index) - 1];
                        $branch_arr1[] = $parent[intval($index) - 1];
                        $branch_arr2[] = $parent[intval($index) - 1];
                    }
                    $x2 += 1;
                    break;
                case 'X3':
                    if ($user_id == $parent[0]) {
                        //如果是直推关系 直推关系加一
                        $x3_1 += 1;
                    }
                    $index = array_search($user_id, $parent);
                    if ($index == 0) {
                        $branch_arr[] = $value['user_id'];
                        $branch_arr1[] = $value['user_id'];
                        $branch_arr2[] = $value['user_id'];
                        $branch_arr3[] = $value['user_id'];
                    }
                    if (intval($index) - 1 >= 0) {
                        $branch_arr[] = $parent[intval($index) - 1];
                        $branch_arr1[] = $parent[intval($index) - 1];
                        $branch_arr2[] = $parent[intval($index) - 1];
                        $branch_arr3[] = $parent[intval($index) - 1];
                    }
                    $x3 += 1;
                    break;
                case 'X4':
                    if ($user_id == $parent[0]) {
                        //如果是直推关系 直推关系加一
                        $x4_1 += 1;
                    }
                    $index = array_search($user_id, $parent);
                    if ($index == 0) {
                        $branch_arr[] = $value['user_id'];
                        $branch_arr1[] = $value['user_id'];
                        $branch_arr2[] = $value['user_id'];
                        $branch_arr3[] = $value['user_id'];
                        $branch_arr4[] = $value['user_id'];
                    }
                    if (intval($index) - 1 >= 0) {
                        $branch_arr[] = $parent[intval($index) - 1];
                        $branch_arr1[] = $parent[intval($index) - 1];
                        $branch_arr2[] = $parent[intval($index) - 1];
                        $branch_arr3[] = $parent[intval($index) - 1];
                        $branch_arr4[] = $parent[intval($index) - 1];
                    }
                    $x4 += 1;
                    break;
            }

        }

        $vs_1 = $v_1 + $v2_1 + $x1_1 + $x2_1 + $x3_1 + $x4_1;//直推VIP个数
        $v2_count = $v2 + $x1 + $x2 + $x3 + $x4;
        $x1_count = $x1 + $x2 + $x3 + $x4;
        $x2_count = $x2 + $x3 + $x4;
        $x3_count = $x3 + $x4;
        $x4_count = $x4;
        $branch_arr = array_unique($branch_arr);
        $branch_arr1 = array_unique($branch_arr1);
        $branch_arr2 = array_unique($branch_arr2);
        $branch_arr3 = array_unique($branch_arr3);
        $branch_arr4 = array_unique($branch_arr4);
//        print_r($v_1);
//        print_r($v2 . "|");
//        print_r($vs_1 . "|");
//        print_r($v2_count . "|");
//        print_r($x1_count . "|");
//        print_r($x2_count . "|");
//        print_r($x3_count . "|");
//        print_r(count($branch_arr));
        $level = "";
        switch ($temp_data['level']) {
            case 'V':
                if ($vs_1 >= self::$CONDITION['V1']['num_line'] && $vs_1 >= self::$CONDITION['V1']['num']) {
                    $level = "V1";
                }
                break;
            case 'V1':
                if ($vs_1 >= self::$CONDITION['V2']['num_line'] && $vs_1 >= self::$CONDITION['V2']['num']) {
                    $level = "V2";
                }
                break;
            case 'V2':
                if (count($branch_arr) >= self::$CONDITION['X1']['num_line'] && $v2_count >= self::$CONDITION['X1']['num']) {
                    $level = "X1";
                }
                break;
            case 'X1':
                if (count($branch_arr1) >= self::$CONDITION['X2']['num_line'] && $x1_count >= self::$CONDITION['X2']['num']) {
                    $level = "X2";
                }
                break;
            case 'X2':
                if (count($branch_arr2) >= self::$CONDITION['X3']['num_line'] && $x2_count >= self::$CONDITION['X3']['num']) {
                    $level = "X3";
                }
                break;
            case 'X3':
                if (count($branch_arr3) >= self::$CONDITION['X4']['num_line'] && $x3_count >= self::$CONDITION['X4']['num']) {
                    $level = "X4";
                }
                break;
        }
        if (!empty($level)) {
            $in_update = [
                'level' => $level
            ];
            self::where('user_id', $user_id)->update($in_update);
            UserModel::setPopLevel([$user_id], $level);
            self::upChildrenSubset($user_id);
        }
    }

    /**
     * 添加用户父级关系数据
     * @param string $user_id
     * @param string $level
     * @return bool|static
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addParent($user_id = '', $level = 'C')
    {
        $data_temp = $this->where('user_id', $user_id)->field('user_id')->find();
        if (empty($data_temp)) {
            $parent = UserModel::getAllParent($user_id);
            $in_data = [
                'time' => time(),
                'user_id' => $user_id,
                'parent' => json_encode($parent),
                'level' => $level
            ];
            return $this->save($in_data);
        } else {
            $parent = UserModel::getAllParent($user_id);
            $in_data = [
                'parent' => json_encode($parent)
            ];
            return $this->where('user_id', $user_id)->update($in_data);
        }
    }

    /**
     * 获取团队分佣的列表
     * @param string $user_id
     * @param array $user_level
     * @param float $price 分佣奖金池
     * @param float $limit 最小截止分佣
     * @param int $lose 0正向 1负向
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTeamParentlevel($user_id = '', $user_level = [], $price = 0.00, $limit = 0.01, $lose = 0)
    {
        $parent_item = self::where('user_id', $user_id)->find();
        $parent_arr_temp = json_decode($parent_item['parent'], true);
        $parent_arr = [];
        if (intval($lose) == 1) {
            //如果是负向商城 过滤掉
            foreach ($parent_arr_temp as $value) {
                if (GameProcessModel::isLastWeek($value, 20)) {
                    $parent_arr[] = $value;
                }
            }
        } else {
            $parent_arr = $parent_arr_temp;
        }
        if (empty($parent_arr)) {
            return [];
        }
        $parent_list = self::whereIn('user_id', $parent_arr)->field('user_id,level,vip')->select();
        $parent_arr_item = [];
        foreach ($parent_list as $value) {
            $parent_arr_item[intval($value['user_id'])] = $value;
        }
//        print_r(json_encode($parent_arr_item,true));
//        exit();
        //将父集关系排序
//        $parent_arr_sort = [];
        $brokerage_user = [];
        $max_level = self::$CONDITION['X1']['level'];//最高的星级
        $max_level_min = self::$CONDITION['X1']['level'];//出现4星以前的最高的星级
        foreach ($parent_arr as $value) {
            $parent_temp = $parent_arr_item[intval($value)];
            //精英奖结算 核心管理奖
            if (intval($parent_temp['vip']) > 0) {
                if (intval($parent_temp['vip']) == 1) {
                    //1精英奖
                    $brokerage_user[] = [
                        'user_id' => $parent_temp['user_id'],
                        'level' => $parent_temp['level'],//分佣级别
                        'relation_level' => 3,//关系级别 0正常下级 1平级 2越级 3精英 4核心管理奖
                        'return_cash' => 4
                    ];
                }
                if (intval($parent_temp['vip']) == 2) {
                    //2 核心管理奖
                    $brokerage_user[] = [
                        'user_id' => $parent_temp['user_id'],
                        'level' => $parent_temp['level'],//分佣级别
                        'relation_level' => 4,//关系级别 0正常下级 1平级 2越级 3精英 4核心管理奖
                        'return_cash' => 10
                    ];
                }
            }
            if (self::$CONDITION[$parent_temp['level']]['level'] >= self::$CONDITION['X1']['level']) {
                //一星以上才能参与分佣
                if (!empty($brokerage_user)) {
                    //最后一个参与分佣的父集
                    $temp_last = $brokerage_user[count($brokerage_user) - 1];
                    if ($max_level == self::$CONDITION['X4']['level']) {
                        //越级奖小于阈值不参与分佣
                        if ((($temp_last['return_cash'] * 0.1) * $price) / 100 > $limit) {
                            //如果出现了X4 后面的父集都是越级奖励
                            $brokerage_user[] = [
                                'user_id' => $parent_temp['user_id'],
                                'level' => $parent_temp['level'],//分佣级别
                                'relation_level' => 2,//关系级别 0正常下级 1平级 2越级
                                'return_cash' => ($temp_last['return_cash'] * 0.1)
                            ];
                        }
                    } else {
                        //如果没有出现X4 没有越级奖
                        //判断有没有平级奖
                        if (self::$CONDITION[$temp_last['level']]['level'] >= self::$CONDITION[$parent_temp['level']]['level'] && self::$CONDITION[$parent_temp['level']]['level'] == $max_level_min) {
                            //平级奖小于阈值不参与分佣
                            if ((($temp_last['return_cash'] * 0.1) * $price) / 100 > $limit) {
                                //如果出现平级
                                $brokerage_user[] = [
                                    'user_id' => $parent_temp['user_id'],
                                    'level' => $parent_temp['level'],//分佣级别
                                    'relation_level' => 1,//关系级别 0正常下级 1平级 2越级
                                    'return_cash' => $temp_last['return_cash'] * 0.1];
                            }
                        } else {
                            if ((($user_level[self::$CONDITION[$parent_temp['level']]['level']]['return_cash']) * $price) / 100 > $limit) {
                                //正常级别奖
                                $brokerage_user[] = [
                                    'user_id' => $parent_temp['user_id'],
                                    'level' => $parent_temp['level'],//分佣级别
                                    'relation_level' => 0,//关系级别 0正常下级 1平级 2越级
                                    'return_cash' => $user_level[self::$CONDITION[$parent_temp['level']]['level']]['return_cash']];
                            }
                        }
                    }
                    if (self::$CONDITION[$parent_temp['level']]['level'] > $max_level) {
                        //每次记录最大级别
                        $max_level = self::$CONDITION[$parent_temp['level']]['level'];
                    }
                    if (self::$CONDITION[$parent_temp['level']]['level'] < self::$CONDITION['X4']['level']) {
                        //出现4X之前最大的级别
                        $max_level_min = self::$CONDITION[$parent_temp['level']]['level'];
                    }
                } else {
                    $max_level = self::$CONDITION[$parent_temp['level']]['level'];
                    //第一个出现分佣
                    if ((($user_level[self::$CONDITION[$parent_temp['level']]['level']]['return_cash']) * $price) / 100 > $limit) {
                        $brokerage_user[] = [
                            'user_id' => $parent_temp['user_id'],
                            'level' => $parent_temp['level'],//分佣级别
                            'relation_level' => 0,//关系级别 0正常下级 1平级 2越级
                            'return_cash' => $user_level[self::$CONDITION[$parent_temp['level']]['level']]['return_cash']];
                    }
                }

            }
        }
        return $brokerage_user;

    }

    /**
     * 获取团队全部数据
     * @param string $user_id
     * @param int $page
     * @param string $day
     * @param int $limit
     * @param int $lose 0正向  1负向
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTeamAll($user_id = '', $page = 1, $day = '', $limit = 100, $lose = 0)
    {
        $temp_data = UserModel::getNextUserList($user_id, $page, $limit);
        $return_list = [];
        $all_total = 0;
        $sum_all = 0;
        $day_all = 0;
        foreach ($temp_data as $value) {
            $team_all = self::_nextTeamAll($value['id'], true, $lose, $day);
            $all_total = $all_total + $team_all['count'] + 1;
            $sum_all = $sum_all + $team_all['sum_all'];
            $day_all = $day_all + $team_all['day_all'];
            $return_list[] = [
                'sum_all' => $team_all['sum_all'],
                'day_all' => $team_all['day_all'],
                'count' => $team_all['count'],
                'phone' => Util::swPhoneStr($value['phone']),
                'member_level' => $value['member_level'],
                'level' => UserModel::getLevel($value['member_level']),
                'X1' => $team_all['X1'],
                'X2' => $team_all['X2'],
                'X3' => $team_all['X3'],
                'X4' => $team_all['X4'],
            ];
        }
        return [
            'all_total' => $all_total,
            'sum_all' => $sum_all,
            'day_all' => $day_all,
            'list' => $return_list
        ];
    }

    /**
     * 下级团队数据
     * @param $user_id
     * @param bool $is_self 统计是否包含自己
     * @param int $lose 0正向  1负向
     * @param string $day 时间
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function _nextTeamAll($user_id, $is_self = false, $lose = 0, $day = "")
    {
        if (empty($day)) {
            $day = date("Y-m-d");
        }
        $sql = "SELECT `user_id`,`level`,`parent` FROM `t_user_parent` WHERE JSON_CONTAINS(`parent`, '" . $user_id . "', '$')";
        $list = Db::query($sql);
        $x1 = 0;
        $x2 = 0;
        $x3 = 0;
        $x4 = 0;
        $ids = [];
        $count = 0;
        foreach ($list as $value) {
            $count++;
            $ids[] = $value['user_id'];
            switch ($value['level']) {
                case 'X1':
                    $x1++;
                    break;
                case 'X2':
                    $x2++;
                    break;
                case 'X3':
                    $x3++;
                    break;
                case 'X4':
                    $x4++;
                    break;
            }
        }
        if ($is_self) {
            $ids[] = $user_id;
            $parent_item = self::where('user_id', $user_id)->field('level')->find();
            switch ($parent_item['level']) {
                case 'X1':
                    $x1++;
                    break;
                case 'X2':
                    $x2++;
                    break;
                case 'X3':
                    $x3++;
                    break;
                case 'X4':
                    $x4++;
                    break;
            }
        }
//        $sun_all = UserSettlementModel::getSumCount($ids, $lose);
        $time_start = strtotime($day);
        $time_ene = strtotime($day . " 23:59:59");
        if (intval($lose) == 0) {
            $day_all = OrderModel::getUserListCons($ids, $time_start, $time_ene);
            $sum_all = OrderModel::getUserListCons($ids, strtotime("2022-10-09"), time());
        } else {
            $day_all = GameProcessModel::getUserListCons($ids, $time_start, $time_ene);
            $sum_all = GameProcessModel::getUserListCons($ids, strtotime("2022-10-09"), time());
        }
        $out_data['X1'] = $x1;
        $out_data['X2'] = $x2;
        $out_data['X3'] = $x3;
        $out_data['X4'] = $x4;
        $out_data['day_all'] = $day_all;
        $out_data['sum_all'] = $sum_all;
        $out_data['count'] = $count;
        return $out_data;
    }

    /**
     * 清除父级关系
     * @param $user_id
     * @return bool
     */
    public static function clearParent($user_id = '')
    {
        $up_data = [
            'parent' => json_encode([]),
        ];
        $ret = self::where('user_id', $user_id)->update($up_data);
        if ($ret === false) {
            return false;
        }
        return true;
    }
}